package cn.backpackerxl.easyJDBC.util;

import java.lang.reflect.Field;

public final class AddCharRule implements JSONParseRule {
    private boolean isArray;

    @Override
    public boolean evaluate(JSONExpression jsonExpression) {
        boolean eval = false;
        this.isArray = jsonExpression.getField().getType().getTypeName().equals("char[]");
        if (jsonExpression.getTypeof() == Typeof.CHAR || this.isArray) {
            this.apply(jsonExpression.getObject(), jsonExpression.getField(), jsonExpression.getJsonObject());
            eval = true;
        }
        return eval;
    }

    @Override
    public void apply(Object entity, Field field, JSONObject obj) {
        try {
            if (this.isArray) {
                Object[] objects = obj.getArrays().stream().map(JSONObject::getCharValue).toArray();
                char[] arr = new char[objects.length];
                for (int i = 0; i < arr.length; i++) {
                    arr[i] = (char) objects[i];
                }
                field.set(entity, arr);
            } else {
                if (!obj.getStrValue().equals("")) {
                    field.set(entity, obj.getCharValue());
                }
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
